// pages/category/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    selectIndex:0,
    genre:['爱情','永生花','韩式系列','友情','长辈','周边','礼品','多肉植物','向日葵','玫瑰','限量'],
    rightMenu:[],
    rightMenu1:[],
    scrollTop:0,

    
    cart1:{
      genre: "",
      gross: 0,
      image: "",
      price: 0,
      productsell: 0,
      title: "",
      _id: 0,
      num:0,
      checked:false
    }
  },
  obj:{},
  async handleItem(e){
    
    let {index} = e.target.dataset
    let right = this.data.rightMenu
    let that = this
    this.setData({
      selectIndex:index,
      rightMenu:this.data.rightMenu1[index]
    })
  },

  handleItemCart(e){
    //获取缓存中的购物车数组
    this.obj = this.data.rightMenu
    let cart = wx.getStorageSync('cart')||[];
    let right = this.data.rightMenu
    //判断商品对象是否在购物车数组中、
    const {index} = e.currentTarget.dataset; 
    let id = cart.findIndex(v=>v._id === index)
    
    let that = this

    if(id === -1){
      const db = wx.cloud.database()
      db.collection('flower').where({
        _id:index
      }).get({
        success(res){
          console.log(res);
          that.setData({
            cart1:{
             genre: res.data[0].genre,
             gross: res.data[0].gross,
             image: res.data[0].image,
             price: res.data[0].price,
             productsell: res.data[0].productsell,
             title: res.data[0].title,
             _id: res.data[0]._id,
             num:1,
             checked:false
            }
      })
      cart.push(that.data.cart1)
      wx.setStorageSync("cart", cart);
    }
  })
    
    }else{
      cart[id].num++;
      wx.setStorageSync("cart", cart);
    }
    //弹窗提示
    wx.showToast({
      title: '加入成功',
      icon: 'success',
    });
    
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    

    let that = this
    let {genre} = this.data
    //云函数调用
    let right = []
    for (let index = 0; index < genre.length; index++) {
    wx.cloud.callFunction({
      name:'category',
      data:{
        title:genre[index]
      },
      success(res){
        right[index]=res.result.data
        that.setData({
          rightMenu:that.data.rightMenu1[0],
          rightMenu1:right
        })
      },
      fail(err){
        console.log(err);
      },
      
    })
  

  }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})